package cn.iocoder.yudao.module.cmt.service.base;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.cmt.controller.admin.base.vo.*;
import cn.iocoder.yudao.module.cmt.dal.dataobject.base.BaseMerchantInfoDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.cmt.dal.mysql.base.BaseMerchantInfoMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.cmt.enums.ErrorCodeConstants.*;

/**
 * 商户信息 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class BaseMerchantInfoServiceImpl implements BaseMerchantInfoService {

    @Resource
    private BaseMerchantInfoMapper merchantInfoMapper;

    @Override
    public Long createMerchantInfo(BaseMerchantInfoSaveReqVO createReqVO) {
        // 插入
        BaseMerchantInfoDO merchantInfo = BeanUtils.toBean(createReqVO, BaseMerchantInfoDO.class);
        merchantInfoMapper.insert(merchantInfo);
        // 返回
        return merchantInfo.getId();
    }

    @Override
    public void updateMerchantInfo(BaseMerchantInfoSaveReqVO updateReqVO) {
        // 校验存在
        validateMerchantInfoExists(updateReqVO.getId());
        // 更新
        BaseMerchantInfoDO updateObj = BeanUtils.toBean(updateReqVO, BaseMerchantInfoDO.class);
        merchantInfoMapper.updateById(updateObj);
    }

    @Override
    public void deleteMerchantInfo(Long id) {
        // 校验存在
        validateMerchantInfoExists(id);
        // 删除
        merchantInfoMapper.deleteById(id);
    }

    private void validateMerchantInfoExists(Long id) {
        if (merchantInfoMapper.selectById(id) == null) {
            throw exception(MERCHANT_INFO_NOT_EXISTS);
        }
    }

    @Override
    public BaseMerchantInfoDO getMerchantInfo(Long id) {
        return merchantInfoMapper.selectById(id);
    }

    @Override
    public PageResult<BaseMerchantInfoDO> getMerchantInfoPage(BaseMerchantInfoPageReqVO pageReqVO) {
        return merchantInfoMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteMerchantInfoListByIds(List<Long> ids) {
        // 校验存在
        ids.forEach(this::validateMerchantInfoExists);
        // 批量删除
        merchantInfoMapper.deleteBatchIds(ids);
    }

}
